package com.ruoyi.generator.word;


import com.ruoyi.common.utils.StringUtilTool;
import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;
import org.springframework.util.StringUtils;

import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigInteger;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * word模板替换
 */
public class WordTemplateFillData {

    private CustomXWPFDocument xwpfDocument = null;
    private InputStream inputStream = null;
    /**
     * 模板Word路径
     */
    private String templateWordFullPath;
    /**
     * 模板替换数据集合
     */
    private Map<String, Object> wordReplaceParams;

    /**
     * 文件生成路径
     */
    private String newsWordPath;
    /**
     * 导出word名称
     */
    private String fileName;

    /**
     * 样式表
     */
    private Map<String, Map<String, Object>> styles;

    //空构造
    public WordTemplateFillData(){ }
    /**
     * 构造参数
     *
     * @param wordReplaceParams    替换数据集合
     * @param templateWordFullPath 模板位置
     * @param newsWordPath         生成文件路径
     */
    public WordTemplateFillData(Map<String, Object> wordReplaceParams, String templateWordFullPath, String newsWordPath, String fileName) {
        this.wordReplaceParams = wordReplaceParams;
        this.templateWordFullPath = templateWordFullPath;
        this.newsWordPath = newsWordPath;
        this.fileName = fileName;
        this.styles = new HashMap<>();
        if (!StringUtils.isEmpty(templateWordFullPath)) {
            try {
                // 重置替换参数集合
                inputStream = new FileInputStream(templateWordFullPath);
                xwpfDocument = new CustomXWPFDocument(inputStream);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 设置Word文档替换集合
     *
     * @param wordReplaceParams
     */
    public void setWordReplaceParams(Map<String, Object> wordReplaceParams) {
        this.wordReplaceParams = wordReplaceParams;
    }

    /**
     * 设置Word生成位置
     *
     * @param newsWordPath
     */
    public void setNewsWordPath(String newsWordPath) {
        this.newsWordPath = newsWordPath;
    }

    /**
     * 设置模板的位置
     *
     * @param templateWordFullPath
     */
    public void setTemplateWordFullPath(String templateWordFullPath) {
        this.templateWordFullPath = templateWordFullPath;
    }

    /**
     * 设置Word名称
     *
     * @param fileName
     */
    public void setFileName(String fileName) {
        this.fileName = fileName;
    }


    /**
     * 设置样式表
     *
     * @param styles
     */
    public void setStyles(Map<String, Map<String, Object>> styles) {
        this.styles = styles;
    }

    /**
     * 导出Word到目录
     */
    public void exportWord() throws Exception {
        exportWord(this.wordReplaceParams, this.templateWordFullPath, this.newsWordPath, this.fileName);
    }

    /**
     * 导出Word到目录
     */
    public void exportWord(Map<String, Object> wordReplaceParams, String templateWordFullPath, String newsWordPath, String fileName) throws Exception {

        if (StringUtils.isEmpty(templateWordFullPath) || StringUtils.isEmpty(newsWordPath)) {
            throw new NullPointerException("no found params templateWordFullPath or newsWordPath");
        }
        try {
            if (inputStream == null) {
                // 重置替换参数集合
                inputStream = new FileInputStream(templateWordFullPath);
                xwpfDocument = new CustomXWPFDocument(inputStream);
            }
            //CustomXWPFDocument doc = new CustomXWPFDocument();//生成图片的类
            // 替换参数集合
            handleWordBody(xwpfDocument, wordReplaceParams);

            File dir = new File(newsWordPath);
            if (!dir.exists()) {// 判断文件目录是否存在
                dir.mkdirs();
            }
            FileOutputStream fileOutputStream = new FileOutputStream(newsWordPath + "/" + fileName + ".docx");
            xwpfDocument.write(fileOutputStream);
            closeInputStream(inputStream);
            closeOutStream(fileOutputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 替换参数
     *
     * @param xwpfDocument
     * @param wordReplaceParams
     */
    private void handleWordBody(CustomXWPFDocument xwpfDocument, Map<String, Object> wordReplaceParams) {

        //读取word页眉内容
        List<XWPFHeader> headerList = xwpfDocument.getHeaderList();
        for (XWPFHeader xwpfHeader : headerList) {

            Iterator<XWPFParagraph> headerIterator = xwpfHeader.getParagraphs().iterator();
            while (headerIterator.hasNext()) {
                XWPFParagraph next = headerIterator.next();
                this.replaceValue(next, wordReplaceParams, styles.get("headerStyle"),xwpfDocument);
            }
        }

        // 替换正文内容
        Iterator<XWPFParagraph> iterator = xwpfDocument.getParagraphsIterator();
        XWPFParagraph paragraph = null;
        while (iterator.hasNext()) {
            paragraph = iterator.next();
            this.replaceValue(paragraph, wordReplaceParams, styles.get("bodyStyle"),xwpfDocument);
        }


        // 替换World中的Table
        List<XWPFTable> tables = xwpfDocument.getTables();
        if (tables != null && tables.size() > 0) {
            tables.forEach(tab -> {
                List<XWPFTableRow> rows = tab.getRows();
                // 每一行数据项
                rows.forEach(tabRow -> {
                    // 每一条数据
                    List<XWPFTableCell> tableCells = tabRow.getTableCells();
                    tableCells.forEach(tabCells -> {
                        Iterator<XWPFParagraph> cellIterator = tabCells.getParagraphs().iterator();
                        while (cellIterator.hasNext()) {
                            XWPFParagraph next = cellIterator.next();
                            this.replaceValue(next, wordReplaceParams, styles.get("tableStyle"),xwpfDocument);
                        }
                    });
                });

            });
        }
    }


    /**
     * 替换标记字符
     *
     * @param para
     * @param params
     */
    private void  replaceValue(XWPFParagraph para, Map<String, Object> params, Map<String, Object> styles ,CustomXWPFDocument doc) {
        List<XWPFRun> runs = null;
        if (this.matcher(para.getParagraphText()).find()) {
            runs = para.getRuns();
            int start = -1;
            int end = -1;
            String str = "";
            int fontSize = 16;
            String fontFamily = "";
            String fontColor = "";
            for (int i = 0; i < runs.size(); i++) {
                XWPFRun run = runs.get(i);
                String runText = run.toString().trim();
                if (!"".equals(runText)) {
                    if ('$' == runText.charAt(0)) {
                        fontSize = run.getFontSize();
                        fontFamily = run.getFontFamily();
                        fontColor = run.getColor();
                        start = i;
                    }
                    if ((start != -1) && (end == -1)) {
                        str += runText;
                    }
                    if ('}' == runText.charAt(runText.length() - 1)) {
                        if (start != -1) {
                            end = i;
                            break;
                        }
                    }
                }
            }
            if (start != -1) {

                for (int i = start; i < end + 1; i++) {
                    para.removeRun(start);
                }

                XWPFRun createRun = para.insertNewRun(start);

//                for (String key : params.keySet()) {
//                    if (str.equals(key)) {
//                        //判断是否 有数字
//                        // 设置值
//                        String mapValue = (String) params.get(key);
//                        if (!StringUtilTool.HasDigit(mapValue)) {
//                            //不包含数字
//                            createRun.setText((String) params.get(key));
//                            createRun.setFontFamily("方正仿宋_GBK");
//                            createRun.setFontSize(16);
//                        } else {
//                            char[] arr = mapValue.toCharArray();
//                            StringBuffer sb = new StringBuffer();
//                            for (int i = 0; i < arr.length; i++) {
//                                XWPFRun newCreateRun = newCreateRun = para.insertNewRun(start + i);
//
//                                newCreateRun.setText(String.valueOf(arr[i]));
//
//                                if (((arr[i] - '0' >= 0) && (arr[i] - '0' <= 9) || (StringUtilTool.is_alpha(String.valueOf(arr[i]))))) { // 判断为数字 和字母
//                                    newCreateRun.setFontFamily("Times New Roman");
//                                    newCreateRun.setFontSize(16);
//
//                                } else {
//                                    newCreateRun.setFontFamily("方正仿宋_GBK");
//                                    newCreateRun.setFontSize(16);
//                                }
//
//                            }
//
//                        }
//
//                        // 样式表设置
//
////                            createRun.setFontFamily(fontFamily);
////                            createRun.setFontSize(fontSize);
////                            createRun.setColor(fontColor);
//
//                        if (styles != null && styles.size() > 0) {
//                            if (styles.containsKey("fontSize")) {
//                                // 设置字体大小
//                                createRun.setFontSize((int) styles.get("fontSize"));
//                            }
//                            if (styles.containsKey("fontFamily")) {
//                                // 设置字体
//                                createRun.setFontFamily(styles.get("fontFamily").toString());
//                            }
//                            if (styles.containsKey("fontBold")) {
//                                // 是否加粗
//                                createRun.setBold((Boolean) styles.get("fontBold"));
//                            }
//                            if (styles.containsKey("fontColor")) {
//                                // 设置颜色
//                                createRun.setColor(styles.get("fontColor").toString());
//                            }
//                        }
//                        break;
//                    }
//                }

                //生成文字加图片的遍历方式
                for (Map.Entry<String, Object> entry : params.entrySet()) {
                    String key = entry.getKey();
                    if (str.indexOf(key) != -1) {
                        Object value = entry.getValue();
                        if (value instanceof String) {
//                            str = str.replace(key, value.toString());
//                            para.createRun().setText(str, 0);
//                            break;
                            if (str.equals(key)) {
                                //判断是否 有数字
                                // 设置值
                                String mapValue = (String) params.get(key);
                                if("${sendUnitForTitle}".equals(key)){//鉴定报告-正式、其他出版物的标题中的占位元素字体与内容字体不同
                                    if (!StringUtilTool.HasDigit(mapValue)) {
                                        //不包含数字
                                        createRun.setText((String) params.get(key));
                                        createRun.setFontFamily("方正小标宋_GBK");
                                        createRun.setFontSize(22);
                                    } else {
                                        char[] arr = mapValue.toCharArray();
                                        StringBuffer sb = new StringBuffer();
                                        for (int i = 0; i < arr.length; i++) {
                                            XWPFRun newCreateRun = newCreateRun = para.insertNewRun(start + i);

                                            newCreateRun.setText(String.valueOf(arr[i]));

                                            if (((arr[i] - '0' >= 0) && (arr[i] - '0' <= 9) || (StringUtilTool.is_alpha(String.valueOf(arr[i]))))) { // 判断为数字 和字母
                                                newCreateRun.setFontFamily("Times New Roman");
                                                newCreateRun.setFontSize(22);

                                            } else {
                                                newCreateRun.setFontFamily("方正小标宋_GBK");
                                                newCreateRun.setFontSize(22);
                                            }
                                        }
                                    }
                                }else{
                                    if (!StringUtilTool.HasDigit(mapValue)) {
                                        //不包含数字
                                        createRun.setText((String) params.get(key));
                                        createRun.setFontFamily("方正仿宋_GBK");
                                        createRun.setFontSize(16);
                                    } else {
                                        char[] arr = mapValue.toCharArray();
                                        StringBuffer sb = new StringBuffer();
                                        for (int i = 0; i < arr.length; i++) {
                                            XWPFRun newCreateRun = newCreateRun = para.insertNewRun(start + i);

                                            newCreateRun.setText(String.valueOf(arr[i]));

                                            if (((arr[i] - '0' >= 0) && (arr[i] - '0' <= 9) || (StringUtilTool.is_alpha(String.valueOf(arr[i]))))) { // 判断为数字 和字母
                                                newCreateRun.setFontFamily("Times New Roman");
                                                newCreateRun.setFontSize(16);

                                            } else {
                                                newCreateRun.setFontFamily("方正仿宋_GBK");
                                                newCreateRun.setFontSize(16);
                                            }
                                        }
                                    }
                                }

                                // 样式表设置
//                            createRun.setFontFamily(fontFamily);
//                            createRun.setFontSize(fontSize);
//                            createRun.setColor(fontColor);

                                if (styles != null && styles.size() > 0) {
                                    if (styles.containsKey("fontSize")) {
                                        // 设置字体大小
                                        createRun.setFontSize((int) styles.get("fontSize"));
                                    }
                                    if (styles.containsKey("fontFamily")) {
                                        // 设置字体
                                        createRun.setFontFamily(styles.get("fontFamily").toString());
                                    }
                                    if (styles.containsKey("fontBold")) {
                                        // 是否加粗
                                        createRun.setBold((Boolean) styles.get("fontBold"));
                                    }
                                    if (styles.containsKey("fontColor")) {
                                        // 设置颜色
                                        createRun.setColor(styles.get("fontColor").toString());
                                    }
                                }
                                break;
                            }
                        } else if (value instanceof List) {
                            str = str.replace(key, "");
                            List<Map> pic = (List) value;
                            for (int i = 0; i<pic.size();i++){
                                int width = Integer.parseInt(pic.get(i).get("width").toString());
                                int height = Integer.parseInt(pic.get(i).get("height").toString());
                                int picType = getPictureType(pic.get(i).get("type").toString());
                                byte[] byteArray = (byte[]) pic.get(i).get("content");
                                ByteArrayInputStream byteInputStream = new ByteArrayInputStream(byteArray);
                                try {
                                    doc.addPictureData(byteInputStream, picType);
                                    doc.createPicture(doc.getAllPictures().size() - 1, width, height, para);
                                    para.createRun().setText(str, 0);
                                    continue;
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
//                            int width = Integer.parseInt(pic.get("width").toString());
//                            int height = Integer.parseInt(pic.get("height").toString());
//                            int picType = getPictureType(pic.get("type").toString());
//                            byte[] byteArray = (byte[]) pic.get("content");
//                            ByteArrayInputStream byteInputStream = new ByteArrayInputStream(byteArray);
//                            try {
//                                //int ind = doc.addPicture(byteInputStream,picType);
//                                //doc.createPicture(ind, width , height,para);
//                                doc.addPictureData(byteInputStream, picType);
//                                doc.createPicture(doc.getAllPictures().size() - 1, width, height, para);
//                                para.createRun().setText(str, 0);
//                                break;
//                            } catch (Exception e) {
//                                e.printStackTrace();
//                            }
                        }
                    }
                }
            }
        }
    }

    /**
     * 正则匹配字符串
     *
     * @param str
     * @return
     */
    private Matcher matcher(String str) {
        Pattern pattern = Pattern.compile("\\$\\{(.+?)\\}", Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(str);
        return matcher;
    }

    /**
     * 根据图片类型，取得对应的图片类型代码
     *
     * @param picType
     * @return int
     */
    private static int getPictureType(String picType) {
        int res = CustomXWPFDocument.PICTURE_TYPE_PICT;
        if (picType != null) {
            if (picType.equalsIgnoreCase("png")) {
                res = CustomXWPFDocument.PICTURE_TYPE_PNG;
            } else if (picType.equalsIgnoreCase("dib")) {
                res = CustomXWPFDocument.PICTURE_TYPE_DIB;
            } else if (picType.equalsIgnoreCase("emf")) {
                res = CustomXWPFDocument.PICTURE_TYPE_EMF;
            } else if (picType.equalsIgnoreCase("jpg") || picType.equalsIgnoreCase("jpeg")) {
                res = CustomXWPFDocument.PICTURE_TYPE_JPEG;
            } else if (picType.equalsIgnoreCase("wmf")) {
                res = CustomXWPFDocument.PICTURE_TYPE_WMF;
            }
        }
        return res;
    }

    /**
     * 将输入流中的数据写入字节数组
     *
     * @param in
     * @return
     */
    public static byte[] inputStream2ByteArray(InputStream in, boolean isClose) {
        byte[] byteArray = null;
        try {
            int total = in.available();
            byteArray = new byte[total];
            in.read(byteArray);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (isClose) {
                try {
                    in.close();
                } catch (Exception e2) {
                    e2.getStackTrace();
                }
            }
        }
        return byteArray;
    }

    /**
     * 关闭输入流
     *
     * @param inputStream
     */
    public void closeInputStream(InputStream inputStream) {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 关闭输出流
     *
     * @param outputStream
     */
    public void closeOutStream(OutputStream outputStream) {
        if (outputStream != null) {
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * Word中添加表格
     *
     * @param title      表格标题
     * @param tableMap   设置表头列和取数据的getXxx();
     * @param paramsList 数据集合
     * @param <T>        对象类型
     * @throws NoSuchMethodException
     * @throws InvocationTargetException
     * @throws IllegalAccessException
     */
    public <T> void createParamTable(String title, Map<String, String> tableMap, List<T> paramsList) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        List<String> funcKeyList = new LinkedList<>();

        // 文档对象不为空
        if (xwpfDocument != null) {
            if (paramsList != null && paramsList.size() > 0) {
                XWPFTable ComTable = setTableHead(title, tableMap, funcKeyList);
                Class<?> t = paramsList.get(0).getClass();
                for (int i = 0; i < paramsList.size(); i++) {
                    XWPFTableRow comTableRow = ComTable.createRow();
                    for (int j = 0; j < funcKeyList.size(); j++) {
                        Method cellMethod = t.getDeclaredMethod(funcKeyList.get(j));
                        // 获取数据
                        Object invokeVal = cellMethod.invoke(paramsList.get(i));
                        if (invokeVal != null) {
                            // 设置表格数据
                            comTableRow.getCell(j).setText(String.valueOf(invokeVal));
                        }
                    }
                }
                //换行
                XWPFParagraph paragraph2 = xwpfDocument.createParagraph();
                XWPFRun paragraphRun2 = paragraph2.createRun();
                paragraphRun2.setText("\r");
            } else {
                System.out.println("参数为空，或者集合为空!");
            }
        } else {
            System.out.println("文档对象空指针!");
        }
    }

    /**
     * 设置表头信息
     *
     * @param title
     * @param tableMap
     * @param funcKeyList
     * @return
     */
    private XWPFTable setTableHead(String title, Map<String, String> tableMap, List<String> funcKeyList) {
        //两个表格之间加个换行
        XWPFParagraph paragraph = xwpfDocument.createParagraph();
        XWPFRun paragraphRun = paragraph.createRun();
        paragraphRun.setText("\r");
        //添加标题，
        XWPFParagraph titleParagraph = xwpfDocument.createParagraph();
        //设置段落居中
        titleParagraph.setAlignment(ParagraphAlignment.CENTER);

        XWPFRun titleParagraphRun = titleParagraph.createRun();
        titleParagraphRun.setText(title);
        titleParagraphRun.setColor("000000");
        titleParagraphRun.setFontSize(24);
        titleParagraphRun.setFontFamily("宋体");
        //换行
        XWPFParagraph paragraph1 = xwpfDocument.createParagraph();
        XWPFRun paragraphRun1 = paragraph1.createRun();
        paragraphRun1.setText("\r");

        //表格部分
        XWPFTable ComTable = xwpfDocument.createTable();
        //列宽自动分割
        CTTblWidth comTableWidth = ComTable.getCTTbl().addNewTblPr().addNewTblW();
        comTableWidth.setType(STTblWidth.DXA);
        comTableWidth.setW(BigInteger.valueOf(9072));

        //表格第一行
        XWPFTableRow comTableRowOne = ComTable.getRow(0);
        AtomicInteger i = new AtomicInteger();
        tableMap.forEach((key, val) -> {
            if (i.get() == 0) {
                comTableRowOne.getCell(0).setText(val);
            } else {
                comTableRowOne.addNewTableCell().setText(val);
            }
            i.getAndIncrement();
            funcKeyList.add(key);
        });
        return ComTable;
    }

    /**
     * 创建表格
     *
     * @param tableIndex   第几个表格
     * @param startRow     开始插入的行数
     * @param cellCount    每行多少列
     * @param newLineTitle 文号信息
     * @param dataList     数据集合
     */
    public void createTableLine(int tableIndex, int startRow, int cellCount, String newLineTitle, List<String> dataList) {
        List<XWPFTable> tables = xwpfDocument.getTables();
        if (tables != null && tables.size() > 0) {
            XWPFTable currentTable = tables.get(tableIndex);
            insertNewLineTable(currentTable, startRow, cellCount, newLineTitle, dataList);
        }
    }

    /**
     * 插入新行
     *
     * @param table
     * @param startRow
     * @param cellCount
     * @param newLineTitle
     * @param dataList
     */
    private void insertNewLineTable(XWPFTable table, int startRow, int cellCount, String newLineTitle, List<String> dataList) {
        int index = 0;
        for (int i = 0; i < dataList.size(); i++) {
            index = startRow + i;
            XWPFTableRow newRow = table.insertNewTableRow(index);
            for (int j = 1; j <= cellCount; j++) {
                XWPFTableCell nowCell = newRow.createCell();
                CTTcPr ctTcPr = nowCell.getCTTc().addNewTcPr();
                setCellBorder(ctTcPr.addNewTcBorders());
                // 设置垂直居中
                nowCell.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER);
                // 获取样式
                XWPFParagraph paragraphArray = nowCell.getParagraphArray(0);
                if (j == 2) {
                    setTableNewLineStyle(paragraphArray, 15, newLineTitle);
                } else if (j == 3) {
                    // 设置每行文号信息
                    setTableNewLineStyle(paragraphArray, 15, dataList.get(i).toString());
                }
            }
            // 合并单元格（合并后面两个单元格）
            mergeCellsHorizontal(table, index, cellCount - 2, cellCount - 1);
        }
        mergeCellsVertically(table, 0, (startRow - 1), index + 1);
        mergeCellsVertically(table, 1, startRow, index + 1);
        // 删除行号标记
        table.removeRow(dataList.size() + startRow);
    }

    /**
     * 合并行
     *
     * @param table
     * @param row
     * @param fromCell
     * @param toCell
     */
    public void mergeCellsHorizontal(XWPFTable table, int row, int fromCell, int toCell) {
        for (int cellIndex = fromCell; cellIndex <= toCell; cellIndex++) {
            XWPFTableCell cell = table.getRow(row).getCell(cellIndex);
            if (cellIndex == fromCell) {
                cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.RESTART);
            } else {
                cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.CONTINUE);
            }
        }
    }

    /**
     * 合并列
     *
     * @param table
     * @param col
     * @param fromRow
     * @param toRow
     */
    public void mergeCellsVertically(XWPFTable table, int col, int fromRow, int toRow) {
        for (int rowIndex = fromRow; rowIndex <= toRow; rowIndex++) {
            XWPFTableCell cell = table.getRow(rowIndex).getCell(col);
            if (rowIndex == fromRow) {
                cell.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.RESTART);
            } else {
                cell.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.CONTINUE);
            }
        }
    }

    /**
     * 设置表格格式
     *
     * @return
     */
    private XWPFParagraph setTableNewLineStyle(XWPFParagraph paragraph, int fontSize, String text) {
        if (paragraph != null) {
            // 设置水平居中
            paragraph.setAlignment(ParagraphAlignment.CENTER);
            // 垂直居中
            paragraph.setVerticalAlignment(TextAlignment.CENTER);
            XWPFRun run = paragraph.createRun();
            run.setFontSize(fontSize);
            if ("文号".equals(text)){
                run.setFontFamily("方正楷体_GBK");
                run.setFontSize(16);
                run.setText(text);

            }else{

                if (!StringUtilTool.HasDigit(text)) {
                    //不包含数字
                    run.setFontFamily("方正仿宋_GBK");
                    run.setFontSize(16);
                    run.setText(text);

                } else {
                    char[] arr = text.toCharArray();
                    StringBuffer sb = new StringBuffer();
                    for (int i = 0; i < arr.length; i++) {
                        XWPFRun newCreateRun = newCreateRun = paragraph.insertNewRun(i);


                        newCreateRun.setText(String.valueOf(arr[i]));


                        if (((arr[i] - '0' >= 0) && (arr[i] - '0' <= 9) || (StringUtilTool.is_alpha(String.valueOf(arr[i]))))) { // 判断为数字 和字母
                            newCreateRun.setFontFamily("Times New Roman");
                            newCreateRun.setFontSize(16);

                        } else {
                            newCreateRun.setFontFamily("方正仿宋_GBK");
                            newCreateRun.setFontSize(16);
                        }

                    }

                }
            }
        }
        return paragraph;
    }

    /**
     * 设置cell的边框
     *
     * @param tcBorders
     */
    private void setCellBorder(CTTcBorders tcBorders) {
        CTBorder hCtBorder = tcBorders.addNewInsideH();
        hCtBorder.setVal(STBorder.Enum.forString("single"));
        hCtBorder.setSz(new BigInteger("1"));
        hCtBorder.setColor("000000");
        CTBorder vCtBorder = tcBorders.addNewInsideV();
        vCtBorder.setVal(STBorder.Enum.forString("single"));
        vCtBorder.setSz(new BigInteger("1"));
        vCtBorder.setColor("000000");

        CTBorder lCtBorder = tcBorders.addNewLeft();
        lCtBorder.setVal(STBorder.Enum.forString("single"));
        lCtBorder.setSz(new BigInteger("1"));
        lCtBorder.setColor("000000");

        CTBorder rCtBorder = tcBorders.addNewRight();
        rCtBorder.setVal(STBorder.Enum.forString("single"));
        rCtBorder.setSz(new BigInteger("1"));
        rCtBorder.setColor("000000");
        CTBorder bCtBorder = tcBorders.addNewBottom();
        bCtBorder.setVal(STBorder.Enum.forString("single"));
        bCtBorder.setSz(new BigInteger("1"));
        bCtBorder.setColor("000000");
    }
}
